<template>
  <div>
    <el-dialog :visible.sync="openChargeDefDrawer" title="价格定义" width="70%" top="0" :show-close="false" :close-on-click-modal="false">
      <el-form ref="priceDefinition" :model="priceDefinition">
        <el-row class="price-row clearfix" :gutter="10">
          <!--左侧主类目 变量+主费用+附加费用-->
          <el-col :span="4" class="leftCol">
            <ul class="left-wrapper list-group">
              <li class="list-group-item">
                <el-button class="list-content" @click="activeCard('basicCard', '')">基础信息</el-button>
                <div class="sub-left-wrapper">
                  <ul class="list-group">
                    <li class="list-group-item">
                      <label>货币单位：</label>{{ priceDefinition.currency }}</li>
                    <li class="list-group-item valid-item clearfix">
                      <label>价格有效期</label>
                      <div>从&nbsp;
                        <span>{{ effectiveFromStr }}</span>
                      </div>
                      <div>至&nbsp;
                        <span>{{ effectiveToStr }}</span>
                      </div>
                    </li>
                  </ul>
                </div>
              </li>
              <li class="list-group-item">
                <el-button class="list-content" @click="activeCard('mainCard', '')">物流费用</el-button>
              </li>

              <li class="list-group-item">
                <el-button class="list-content" @click.prevent="activeCard('additionalCharge', '')">附加费用</el-button>
                <div class="sub-left-wrapper">
                  <ul class="list-group">
                    <li v-for="(additionalCharge, index) in priceDefinition.additionalCharges" :key="index" class="list-group-item">
                      <a href="#" class="sub-list-item" @click.prevent="activeCard('additionalCharge', additionalCharge)">{{ chargeSubjectOptionMap.get(additionalCharge.chargeName).name }}</a>
                      <i class="el-icon-delete" title="删除" @click.prevent="deleteExtra(index)" />
                    </li>
                  </ul>
                </div>
              </li>

            </ul>
          </el-col>

          <!--中间操作-->
          <el-col :span="16">
            <div>
              <!--基础信息-->
              <el-card v-show="basicCardActive" header="基础信息">
                <el-form-item label="货币" label-position="top" required>
                  <el-select v-model="priceDefinition.currency" name="currency">
                    <el-option v-for="currency in currencies" :key="currency.name" :label="currency.name" :value="currency.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="价格有效期" label-position="top" required>
                  <el-date-picker
                    v-model="priceDefinition.effectiveFrom"
                    type="datetime"
                    placeholder="开始日期"
                    format="yyyy-MM-dd HH:mm"
                  />
                  <span>&nbsp;至&nbsp;</span>
                  <el-date-picker
                    v-model="priceDefinition.effectiveTo"
                    type="datetime"
                    placeholder="结束日期"
                    format="yyyy-MM-dd HH:mm"
                  />
                </el-form-item>
              </el-card>

              <!--主费用-->
              <el-card v-show="mainCardActive" header="物流费用">
                <el-form-item label="费用名称" label-position="top" required>
                  <el-select v-model="priceDefinition.mainCharge.name" clearable filterable placeholder="如果没有可选项,请先新建费用科目">
                    <el-option v-for="(item, index) in chargeSubjectOptions" :key="index" :value="item.id" :label="item.name" />
                  </el-select>
                </el-form-item>
                <el-radio-group v-model="mainActiveTab" style="margin-bottom: 10px;">
                  <el-radio label="MainCal">计算公式</el-radio>
                  <el-radio label="MainShip">物流价格定义</el-radio>
                </el-radio-group>

                <!--计算公式-->
                <div v-if="mainCardActive && mainCardCalActive">
                  <el-form-item label="销售价" label-position="top">
                    <el-input v-model.lazy="priceDefinition.mainCharge.formula" type="textarea" :rows="3" placeholder="JavaScript语法的一个表达式，也可以引用基本变量和自定义变量" />
                  </el-form-item>
                  <el-form-item label="成本价" label-position="top">
                    <el-input v-model.lazy="priceDefinition.costCharge.formula" type="textarea" :rows="3" placeholder="JavaScript语法的一个表达式，也可以引用基本变量和自定义变量" />
                  </el-form-item>
                </div>
                <!--物流价格定义-->
                <div v-else>

                  <el-form-item>
                    <el-button @click.prevent="activeCard('area', '')">1、定义分区</el-button>
                    <el-button @click.prevent="activeCard('unitWeight', '')">2、定义重量段及费用</el-button>
                    <el-button @click="imporDialogShow = true">模板导入</el-button>
                  </el-form-item>
                  <!-- 定义分区 -->
                  <div v-show="mainCardAreaActive">
                    <el-form-item>
                      <el-button type="primary" @click="mainCardAreaModalActive = true">添加分区</el-button>
                    </el-form-item>
                    <el-form-item>
                      <el-table :data="priceDefinition.mainCharge.logisticPrice.areas" stripe style="width: 100%">
                        <el-table-column prop="code" label="分区编号">
                          <template slot-scope="scope">
                            <div v-if="!mainCardAreaEditing">{{ scope.row.areaCode }}</div>
                            <el-input v-if="mainCardAreaEditing" v-model="scope.row.areaCode" />
                          </template>
                        </el-table-column>
                        <el-table-column prop="country" label="分区国家">
                          <template slot-scope="scope">
                            <div v-if="!mainCardAreaEditing">{{ scope.row.region }}</div>
                            <el-input v-if="mainCardAreaEditing" v-model="priceDefinition.mainCharge.logisticPrice.areas[scope.$index].region" />
                          </template>
                        </el-table-column>
                        <el-table-column label="操作">
                          <template slot-scope="scope">
                            <el-button size="small" shape="circle" type="text" @click="deleteMainCardArea(scope.$index)">删除</el-button>
                          </template>
                        </el-table-column>
                      </el-table>

                    </el-form-item>
                    <el-form-item v-show="priceDefinition.mainCharge.logisticPrice.areas != null && priceDefinition.mainCharge.logisticPrice.areas.length > 0">
                      <el-button size="small" type="warning" @click="mainCardAreaEdit">全部编辑</el-button>
                      <el-button size="small" type="primary" @click="mainCardAreaSave">保存</el-button>
                    </el-form-item>
                  </div>
                  <!-- 重量段及费用 -->
                  <div v-show="mainCardWeightActive">
                    <el-form-item label="分区编号" label-position="top">
                      <el-select
                        v-model="priceDefinition.mainCharge.logisticPrice.selectedAreaCode"
                        placeholder="请选择分区编号"
                        @change="areaCodeChanged"
                      >
                        <el-option
                          v-for="(area, index) in priceDefinition.mainCharge.logisticPrice.areas"
                          :key="index"
                          :value="area.areaCode"
                          :label="area.areaCode"
                        />
                      </el-select>
                      <el-button type="primary" @click="openMainCardWeightModal">添加费用</el-button>
                    </el-form-item>
                    <el-form-item>
                      <el-table :data="mainCardAreaWeightTableBody" stripe style="width: 100%">
                        <el-table-column prop="from" label="重量从(<)">
                          <template slot-scope="scope">
                            <span v-if="!mainCardAreaWeightEditing">{{ scope.row.from }}</span>
                            <el-input v-else v-model="scope.row.from" />
                          </template>
                        </el-table-column>
                        <el-table-column prop="to" label="重量到(<=)">
                          <template slot-scope="scope">
                            <span v-if="!mainCardAreaWeightEditing">{{ scope.row.to }}</span>
                            <el-input v-else v-model="scope.row.to" />
                          </template>
                        </el-table-column>
                        <el-table-column prop="unitWeight" label="计费重量单位">
                          <template slot-scope="scope">
                            <span v-if="!mainCardAreaWeightEditing">{{ scope.row.unitWeight }}</span>
                            <el-input v-else v-model="scope.row.unitWeight" />
                          </template>
                        </el-table-column>
                        <el-table-column prop="chargeType" label="费用定义分类">
                          <template slot-scope="scope">
                            <el-select v-if="mainCardAreaWeightEditing" v-model="scope.row.chargeType" name="currency" style="width: 100%;" placeholder="请选择费用定义分类">
                              <el-option v-for="(chargeType, index) in chargeTypes" :key="index" :value="chargeType.value" :label="chargeType.name" />
                            </el-select>
                            <div v-else>
                              <span v-if="'COST' === scope.row.chargeType">成本</span>
                              <span v-else-if="'CONSTANT' === scope.row.chargeType">固定费用</span>
                              <span v-else-if="'UNITPRICE' === scope.row.chargeType">简单单价（重量*单价）</span>
                              <span v-else-if="'CHAINED' === scope.row.chargeType">续重单价（除扣前一个重量段剩下的重量 * 单价）</span>
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column prop="price" label="重量段费用">
                          <template slot-scope="scope">
                            <span v-if="!mainCardAreaWeightEditing">{{ scope.row.price }}</span>
                            <el-input v-else v-model="scope.row.price" type="textarea" :rows="2" />
                          </template>
                        </el-table-column>
                        <el-table-column prop="cost" label="成本价">
                          <template slot-scope="scope">
                            <span v-if="!mainCardAreaWeightEditing">{{ scope.row.costPrice }}</span>
                            <el-input v-else v-model="scope.row.costPrice" type="textarea" :rows="2" />
                          </template>
                        </el-table-column>
                        <el-table-column label="操作">
                          <template slot-scope="scope">
                            <el-button size="small" shape="circle" type="text" @click="delMainCardAreaWeightPrice(scope.$index)">删除</el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-form-item>
                    <el-form-item
                      v-show="priceDefinition.mainCharge.logisticPrice.prices[priceDefinition.mainCharge.logisticPrice.selectedAreaCode] != null
                        && priceDefinition.mainCharge.logisticPrice.prices[priceDefinition.mainCharge.logisticPrice.selectedAreaCode].length > 0"
                    >
                      <el-button size="small" type="warning" @click="editPrice">全部编辑</el-button>
                      <el-button v-if="mainCardAreaWeightEditing" size="small" type="primary" @click="savePrice()">保存</el-button>
                    </el-form-item>
                  </div>
                </div>
              </el-card>

              <!--附加费用-->
              <el-card v-show="extraCardActive" header="附加费用">
                <el-form-item label="费用名称" label-position="top" required>
                  <el-select v-model="newExtra.chargeName" clearable filterable placeholder="如果没有可选项,请先新建费用科目">
                    <el-option v-for="(item, index) in chargeSubjectOptions" :key="index" :value="item.id" :label="item.name" />
                  </el-select>
                </el-form-item>
                <el-form-item label="计算公式" label-position="top" required>
                  <el-input v-model="newExtra.formula" type="textarea" :rows="4" placeholder="JavaScript语法的一个表达式" />
                </el-form-item>
                <el-form-item label-position="top">
                  <el-button size="small" type="primary" @click="addExtra">确认</el-button>
                  <el-button size="small" @click.prevent="resetAddExtra">重置</el-button>
                </el-form-item>
              </el-card>
            </div>
          </el-col>

          <!--右侧说明部分-->
          <el-col :span="4">
            <el-card header="基本变量">
              <!--基本变量-->
              <el-collapse>
                <el-collapse-item v-for="(item, index) in basicVariables" :key="index" :title="item.name">
                  <div style="margin-top: 10px;">{{ item.describe }}</div>
                </el-collapse-item>
              </el-collapse>
            </el-card>
          </el-col>
        </el-row>
        <!--添加国家分区-弹出层-->
        <el-dialog :visible.sync="mainCardAreaModalActive" title="添加分区" top="0" :close-on-click-modal="false" :modal="false">
          <el-form :model="newArea" size="small">
            <el-form-item label="分区编号" label-position="top">
              <el-input v-model.lazy="newArea.areaCode" placeholder="请输入分区编号，如 “US001”" />
            </el-form-item>
            <el-form-item label="分区国家" label-position="top">
              <el-input v-model.lazy="newArea.region" type="textarea" :rows="4" placeholder="请输入分区国家二位简码" />
            </el-form-item>
          </el-form>
          <div>
            <p>示例：</p>
            <p>1、<b>US</b> 表示全美国，US是国家简码</p>
            <p>2、<b>US(@[8|9])</b> 8|9是以8或者9开头的邮编，US是国家简码，(),@,[]是必须的</p>
            <p>3、<b>US(@[07001~07003])</b> 07001~07003是指07001到07003的区间，包含07001,07002,07003，US是国家简码，(),@,[]是必须的</p>
            <p>4、<b>US(@[60433,85043])</b> 邮编用逗号分隔，US是国家简码，(),@,[]是必须的</p>
            <p>5、<b>US(@[005|010])</b> 005|010是以005或者010开头的邮编，US是国家简码，(),@,[]是必须的</p>
          </div>
          <div slot="footer">
            <el-button size="small" @click="closeMainCardAreaModal()">取 消</el-button>
            <el-button size="small" type="primary" @click="mainCardCreateArea()">确 定</el-button>
          </div>
        </el-dialog>
        <!--添加重量段及费用-弹出层-->
        <el-dialog :visible.sync="mainCardWeightModalActive" title="添加重量段及费用" top="0" :close-on-click-modal="false" :modal="false">
          <el-form :model="newPrice" size="small">
            <el-form-item label="重量从" label-position="top">
              <el-input v-model="newPrice.from" type="number" placeholder="如 “0.0”" />
            </el-form-item>
            <el-form-item label="重量到" label-position="top">
              <el-input v-model="newPrice.to" type="number" placeholder="如 “1.0”" />
            </el-form-item>
            <el-form-item label="计费重量单位" label-position="top">
              <el-input v-model="newPrice.unitWeight" type="number" placeholder="如 “1" />
            </el-form-item>
            <el-form-item label="费用定义分类" label-position="top">
              <el-select v-model="newPrice.chargeType" style="width: 100%;" placeholder="请选择费用定义分类">
                <el-option v-for="(chargeType, index) in chargeTypes" :key="index" :value="chargeType.value" :label="chargeType.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="重量段费用" label-position="top">
              <el-input v-model="newPrice.price" type="number" :rows="2" placeholder="一个数值" />
            </el-form-item>
            <el-form-item label="成本价" label-position="top">
              <el-input v-model="newPrice.costPrice" type="number" :rows="2" placeholder="如 “19.8”" />
            </el-form-item>
          </el-form>
          <div slot="footer">
            <el-button size="small" type="warning" @click="createPriceAndContinue">确定并继续添加</el-button>
            <el-button size="small" @click="mainCardWeightModalActive = false">取消</el-button>
            <el-button size="small" @click="createPrice">确认</el-button>
          </div>
        </el-dialog>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="margin-right: 8px" @click="closeDefDrawer">取消</el-button>
        <el-button type="primary" @click="commitPriceDefinition">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="上传报价" :visible.sync="imporDialogShow" width="30%">
      <el-upload :action="importUrl" :on-success="importCallBack" name="file" :limit="1" :file-list="fileList" accept=".xlsx" :with-credentials="true" :show-file-list="false" style="display: inline-block;">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      </el-upload>
      <a href="/template/price_definition.xlsx" download="报价模板.xlsx" style="margin-left:50px;display: inline-block; vertical-align: top;">
        <el-button size="small" type="text">下载模板</el-button>
      </a>
    </el-dialog>
  </div>
</template>

<script>
import dateFormat from 'dateformat'
import { copyProperty } from '@/utils/tools'
import config from '@/settings'
const BASE_URL = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro
export default {
  props: {
    openChargeDefDrawer: Boolean,
    initData: {
      type: Object
    },
    parentCloseDefDrawer: {
      type: Function,
      required: true
    },
    chargeDefCallBack: {
      type: Function,
      required: true
    },
    weightUnit: {
      type: String,
      required: true
    },
    discount: {
      type: String,
      default: '0'
    },
    basicVariables: {
      type: [Array]
    },
    chargeSubjectOptions: {
      type: [Array]
    }
  },
  data() {
    return {
      fileList: [],
      importUrl: BASE_URL + '/product/parse',
      imporDialogShow: false,
      mainActiveTab: '',
      listStyle: {
        'margin-top': '10px'
      },
      mainCardAreaWeightTableBody: [],
      mainCardWeightModalActive: false,
      mainCardAreaModalActive: false,
      isTestPriceFailed: false,
      priceDefinitionDefault: {
        currency: 'CNY',
        effectiveFrom: '',
        effectiveTo: '',
        mainCharge: {
          name: '',
          cal: 'JS',
          formula: '',
          logisticPrice: {
            minBillableWeight: '',
            selectedAreaCode: '',
            weightUnit: 'KG',
            areas: [],
            prices: {}
          }
        },
        costCharge: {
          name: 'costCharge',
          formula: ''
        },
        additionalCharges: [],
        userDefinedVariables: []
      },
      priceDefinition: {
        currency: 'CNY',
        effectiveFrom: '',
        effectiveTo: '',
        mainCharge: {
          name: '',
          cal: 'JS',
          formula: '',
          logisticPrice: {
            minBillableWeight: '',
            selectedAreaCode: '',
            weightUnit: 'KG',
            areas: [],
            prices: {}
          }
        },
        costCharge: {
          name: 'costCharge',
          formula: ''
        },
        additionalCharges: [],
        userDefinedVariables: []
      },
      preCheck: true,
      mainCardAreaEditing: false,
      mainCardAreaWeightEditing: false,
      mainCardAreaActive: true,
      mainCardWeightActive: false,
      basicCardActive: true,
      customCardActive: false,
      mainCardActive: false,
      extraCardActive: false,
      mainCardCalActive: true,
      additionalChargeEditing: false,
      oldAdditionalCharge: {},
      weightUnits: [
        { name: 'KG', value: 'KG' },
        { name: 'Pounds', value: 'POUNDS' },
        { name: 'Ounce', value: 'OZ' }
      ],
      chargeTypes: [
        { name: '固定费用', value: 'CONSTANT' },
        { name: '简单单价（重量*单价）', value: 'UNITPRICE' },
        {
          name: '续重单价（除扣前一个重量段剩下的重量 * 单价）',
          value: 'CHAINED'
        }
      ],
      currencies: [
        { name: '美元', value: 'USD' },
        { name: '欧元', value: 'EUR' },
        { name: '人民币', value: 'CNY' },
        { name: '港币', value: 'HKD' },
        { name: '日元', value: 'JPY' },
        { name: '英镑', value: 'GBP' }
      ],
      newArea: {
        areaCode: '',
        region: ''
      },
      newExtra: {
        name: '',
        chargeName: '',
        condition: '',
        formula: ''
      },
      newPriceDefault: {
        areaCode: '',
        from: 0,
        to: '',
        unitWeight: 1,
        price: '',
        costPrice: 0,
        chargeType: ''
      },
      newPrice: {
        areaCode: '',
        from: 0,
        to: '',
        unitWeight: 1,
        price: '',
        costPrice: 0,
        chargeType: ''
      },
      priceTestResult: [],
      file: ''
    }
  },
  computed: {
    effectiveFromStr: {
      get() {
        return this.priceDefinition.effectiveFrom ? dateFormat(this.priceDefinition.effectiveFrom, 'yyyy-mm-dd HH:ss') : ''
      }
    },
    effectiveToStr: {
      get() {
        return this.priceDefinition.effectiveTo ? dateFormat(this.priceDefinition.effectiveTo, 'yyyy-mm-dd HH:ss') : ''
      }
    },
    chargeSubjectOptionMap: {
      get() {
        const map = new Map()
        this.chargeSubjectOptions.forEach(ele => {
          map.set(ele.id, ele)
        })
        return map
      }
    },
    editing: {
      get() {
        return this.initData.editing
      }
    }
  },
  watch: {
    mainActiveTab: function() {
      switch (this.mainActiveTab) {
        case 'MainCal': {
          this.priceDefinition.mainCharge.cal = 'JS'
          this.mainCardActive = true
          this.mainCardCalActive = true
          break
        }
        case 'MainShip': {
          this.priceDefinition.mainCharge.cal = 'SHIPMENT'
          this.mainCardActive = true
          this.mainCardCalActive = false
          break
        }
      }
    },
    editing: function() {
      if (this.initData.editing) {
        copyProperty(this.priceDefinition, this.initData)
      } else {
        this.reset()
      }
    }
  },
  created() {
    if (this.initData.mainCharge) {
      this.priceDefinition = this.initData
      if (this.priceDefinition.mainCharge.cal === 'JS') {
        this.mainCardCalActive = true
      } else if (this.priceDefinition.mainCharge.cal === 'SHIPMENT') {
        this.mainCardCalActive = false
      }
    }
  },
  methods: {
    importCallBack(res) {
      if (res.success) {
        this.$message.success('成功')
        this.imporDialogShow = false
        this.fileList = []
        this.priceDefinition.mainCharge.logisticPrice.areas = res.data.areas
        this.priceDefinition.mainCharge.logisticPrice.prices = res.data.prices
      } else {
        this.fileList = []
        this.$message({
          message: res.message,
          type: 'error',
          duration: 0,
          showClose: true
        })
      }
    },
    openMainCardWeightModal() {
      if (!this.priceDefinition.mainCharge.logisticPrice.selectedAreaCode) {
        this.$Notice.error({
          desc: '请先选择分区编号',
          duration: 0
        })
      } else {
        this.mainCardWeightModalActive = true
      }
    },
    closeDefDrawer() {
      this.parentCloseDefDrawer()
    },
    // 清空测试
    resetTestPrice() {
      this.priceTestResult = []
      this.$refs.testPriceFile.value = ''
      this.isTestPriceFailed = false
    },
    mainCardAreaEdit() {
      this.mainCardAreaEditing = true
      this.$nextTick(function() {
        this.$el.focus()
      })
    },
    editPrice() {
      this.mainCardAreaWeightEditing = true
      this.$nextTick(function() {
        this.$el.focus()
      })
    },
    mainCardAreaSave() {
      for (const area of this.priceDefinition.mainCharge.logisticPrice.areas) {
        area.region = area.region.trim().replace(/，/g, ',')
      }
      this.mainCardAreaEditing = false
    },
    savePrice(data) {
      this.mainCardAreaWeightEditing = false
    },
    commitPriceDefinition() {
      if (!this.checkData(this.priceDefinition)) {
        return
      }

      if (this.priceDefinition.mainCharge.formula && this.priceDefinition.mainCharge.formula.trim() !== '') {
        this.priceDefinition.mainCharge.cal = 'JS'
      } else {
        this.priceDefinition.mainCharge.cal = 'SHIPMENT'
      }
      this.priceDefinition.mainCharge.logisticPrice.weightUnit = this.weightUnit
      this.doCommmit()
    },
    doCommmit() {
      this.$confirm('确定要提交价格', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.isTestPriceFailed = false
        this.basicCardActive = true
        this.customCardActive = false
        this.mainCardActive = false
        this.extraCardActive = false
        this.priceDefinition.effectiveFrom = dateFormat(this.priceDefinition.effectiveFrom, 'yyyy-mm-dd HH:ss') + ':00'
        this.priceDefinition.effectiveTo = dateFormat(this.priceDefinition.effectiveTo, 'yyyy-mm-dd HH:ss') + ':00'
        this.chargeDefCallBack(this.priceDefinition)
        this.reset()
      })
    },
    reset() {
      copyProperty(this.priceDefinition, this.priceDefinitionDefault)
      this.mainCardAreaWeightTableBody = []
      this.priceDefinition.mainCharge.logisticPrice.selectedAreaCode = ''
    },
    checkData(data) {
      if (data.currency === '') {
        this.$message({
          showClose: true,
          message: '请选择币种',
          type: 'error',
          duration: 0
        })
        return false
      }
      if (data.effectiveFrom === '' || data.effectiveTo === '') {
        this.$message({
          showClose: true,
          message: '请补全价格有效期',
          type: 'error',
          duration: 0
        })
        return false
      }
      if (data.effectiveFrom > data.effectiveTo) {
        this.$message({
          showClose: true,
          message: '价格开始日期必须小于结束日期',
          type: 'error',
          duration: 0
        })
        return false
      }
      const validAreas = data.mainCharge.logisticPrice.areas
      const validSaleFormula = data.mainCharge.formula
      const validCostFormula = data.costCharge.formula
      if (
        validAreas.length > 0 &&
        ((validSaleFormula && validSaleFormula !== '') || (validCostFormula && validCostFormula !== ''))
      ) {
        this.$message({
          showClose: true,
          message: '计算公式和物流价格定义二者只能选其一',
          type: 'error',
          duration: 0
        })
        return false
      } else if (
        data.mainCharge.cal === 'JS' &&
        ((validSaleFormula == null || validSaleFormula === '') || (validCostFormula == null || validCostFormula === '')) &&
        validAreas.length === 0
      ) {
        this.$message({
          showClose: true,
          message: '当前选择的是计算公式，成本价和销售价都不能为空',
          type: 'error',
          duration: 0
        })
        return false
      } else if (
        data.mainCharge.cal === 'SHIPMENT' &&
        ((validSaleFormula == null || validSaleFormula === '') || (validCostFormula == null || validCostFormula === '')) &&
        validAreas.length === 0
      ) {
        this.$message({
          showClose: true,
          message: '当前选择的是物流价格定义，请补全对应的分区及重量段费用等信息',
          type: 'error',
          duration: 0
        })
        return false
      } else if (
        validAreas.length === 0 &&
        (validSaleFormula === '' || validSaleFormula == null) &&
        (validCostFormula === '' || validCostFormula == null)
      ) {
        this.$message({
          showClose: true,
          message: '计算公式和物流价格定义二者必选其一',
          type: 'error',
          duration: 0
        })
        return false
      } else if (!data.mainCharge.name) {
        this.$message({
          showClose: true,
          message: '费用名称必填',
          type: 'error',
          duration: 0
        })
        return false
      }

      return true
    },
    // 添加附件费用
    addExtra() {
      var reg = /^[a-zA-Z][a-zA-Z0-9_]*$/
      if (this.additionalChargeEditing) {
        if (!this.newExtra.chargeName || !this.newExtra.formula) {
          this.$message({
            showClose: true,
            message: '请补全附加费用信息',
            type: 'error',
            duration: 0
          })
          return false
        }
        for (const key in this.newExtra) {
          this.oldAdditionalCharge[key] = this.newExtra[key]
        }
      } else {
        if (!this.newExtra.chargeName || !this.newExtra.formula) {
          this.$message({
            showClose: true,
            message: '请补全附加费用信息',
            type: 'error',
            duration: 0
          })
          return false
        }
        this.priceDefinition.additionalCharges.push(this.newExtra)
      }
      this.additionalChargeEditing = false
      this.clearNewExtra()
    },
    resetAddExtra() {
      if (this.additionalChargeEditing) {
        for (const key in this.oldAdditionalCharge) {
          this.newExtra[key] = this.oldAdditionalCharge[key]
        }
      } else {
        this.clearNewExtra()
      }
    },

    clearNewExtra() {
      this.newExtra = { name: '', chargeName: '', condition: '', formula: '' }
    },
    // 添加国家分区
    mainCardCreateArea() {
      const newArea = { areaCode: '', region: '' }
      newArea.areaCode = this.newArea.areaCode
      newArea.region = this.newArea.region
      this.priceDefinition.mainCharge.logisticPrice.areas.push(newArea)
      this.newArea = { areaCode: '', region: '' }
      this.mainCardAreaModalActive = false
    },
    createPriceAndContinue() {
      this._createPrice()
    },

    // 添加重量段及价格
    createPrice() {
      this._createPrice()
      this.mainCardWeightModalActive = false
    },
    _createPrice() {
      const prices = this.priceDefinition.mainCharge.logisticPrice.prices
      const selectedCode = this.priceDefinition.mainCharge.logisticPrice
        .selectedAreaCode
      this.newPrice.areaCode = this.priceDefinition.mainCharge.logisticPrice.selectedAreaCode
      const price = {}
      for (const x in this.newPrice) {
        price[x] = this.newPrice[x]
      }

      if (prices[selectedCode] !== null && prices[selectedCode] !== undefined) {
        prices[selectedCode].push(price)
      } else {
        prices[selectedCode] = [price]
      }
      this.mainCardAreaWeightTableBody = prices[selectedCode]
      this.clearNewPrice()
    },
    clearNewPrice() {
      for (const key in this.newPriceDefault) {
        if (key === 'from') {
          this.newPrice.from = this.newPrice.to
        } else {
          this.newPrice[key] = this.newPriceDefault[key]
        }
      }
    },
    areaCodeChanged(selectedCode) {
      const prices = this.priceDefinition.mainCharge.logisticPrice.prices
      this.mainCardAreaWeightTableBody = prices[selectedCode]
    },
    // 国家分区---删除一行
    deleteMainCardArea(index) {
      delete this.priceDefinition.mainCharge.logisticPrice.prices[
        this.priceDefinition.mainCharge.logisticPrice.areas[index].areaCode
      ]
      this.priceDefinition.mainCharge.logisticPrice.areas.splice(index, 1)
    },
    // 重量段及价格---删除一行
    delMainCardAreaWeightPrice(index) {
      const selectedCode = this.priceDefinition.mainCharge.logisticPrice
        .selectedAreaCode
      const prices = this.priceDefinition.mainCharge.logisticPrice.prices
      prices[selectedCode].splice(index, 1)
    },
    // 自定义变量---删除一条
    deleteVariable(index) {
      this.priceDefinition.userDefinedVariables.splice(index, 1)
    },
    // 附加费用---删除一条
    deleteExtra(index) {
      this.priceDefinition.additionalCharges.splice(index, 1)
    },
    // 选项卡切换
    activeCard(tabName, data) {
      this.customCardActive = false
      this.mainCardActive = false
      this.extraCardActive = false
      this.basicCardActive = false

      // 左侧类目选项卡切换
      if (tabName === 'mainCard') {
        this.mainCardActive = true
        if (this.priceDefinition.mainCharge.formula) {
          this.mainActiveTab = 'MainCal'
        } else {
          this.mainActiveTab = 'MainShip'
        }
        return
      } else if (tabName === 'additionalCharge') {
        if (data !== '') {
          this.oldAdditionalCharge = data
          this.newExtra.name = data.name
          this.newExtra.chargeName = data.chargeName
          this.newExtra.formula = data.formula
          this.newExtra.condition = data.condition
          this.additionalChargeEditing = true
        } else {
          this.additionalChargeEditing = false
          this.clearNewExtra()
        }
        this.extraCardActive = true
        return
      } else if (tabName === 'basicCard') {
        this.basicCardActive = true
        return
      } else if (tabName === 'MainCal') { // 主费用选项卡 计算公式+物流计算公式
        this.priceDefinition.mainCharge.cal = 'JS'
        this.mainCardActive = true
        this.mainCardCalActive = true
        return
      } else if (tabName === 'MainShip') {
        this.priceDefinition.mainCharge.cal = 'SHIPMENT'
        this.mainCardActive = true
        this.mainCardCalActive = false
        return
      }
      this.mainCardAreaActive = false
      this.mainCardWeightActive = false
      // 主费用物流计算公式选项卡切换 分区国家+重量段及费用
      if (tabName === 'area') {
        this.mainCardActive = true
        this.mainCardAreaActive = true
      } else if (tabName === 'unitWeight') {
        this.mainCardActive = true
        this.mainCardAreaActive = false
        this.mainCardWeightActive = true
      }
    },
    getFile(event) {
      this.file = event.target.files[0]
    },
    resetPriceForm() {
      if (this.$refs.parseForm.value !== '') {
        this.$refs.parseForm.value = ''
        this.priceDefinition.mainCharge.logisticPrice.areas = []
      }
    },
    // 关闭添加分区弹出
    closeMainCardAreaModal() {
      this.mainCardAreaModalActive = false
      this.newArea.areaCode = ''
      this.newArea.region = ''
    }
  }
}
</script>

<style lang="scss" scoped>
.price-row {
  // 左侧类目
  .left-wrapper {
    &.list-group {
      margin: 0;
      padding: 1px;
      .list-group-item {
        color: #333;
        border-radius: 0;
        &.active {
          background-color: #fff;
          .btn {
            background-color: #409eff;
            color: #fff;
          }
        }
      }
      > .list-group-item {
        margin: -1px 0 10px 0;
        padding: 0;
        border: 0;
        width: 100%;
        .sub-left-wrapper .list-group .list-group-item {
          color: #333;
        }
        .list-content {
          display: block;
          width: 100%;
          margin-bottom: 0;
          background-color: #fff;
          border: 1px solid #ddd;
          text-align: center;
          font-weight: bold;
          color: #333;
          &:hover,
          &:active,
          &:focus {
            color: #fff;
            background-color: #409eff;
          }
          .glyphicon-plus-sign {
            display: inline-block;
            float: right;
            padding-right: 10px;
            color: #ccc;
            &:hover {
              cursor: pointer;
              color: #fff;
            }
          }
        }
        .sub-left-wrapper {
          .list-group {
            margin: 0;
            padding-top: 10px;
            .list-group-item {
              border: none;
              color: #333;
              width: 100%;
              .sub-list-item:hover,
              .sub-list-item:link,
              .sub-list-item:visited {
                text-decoration: none;
              }
              .delete-icon {
                float: right;
                font-weight: 200;
              }
              label {
                font-weight: normal;
              }
              &.valid-item {
                .valid-time {
                  float: left;
                  span {
                    display: block;
                    b {
                      display: inline-block;
                      margin-left: 5px;
                      margin-right: 5px;
                      font-weight: normal;
                    }
                  }
                }
              }
            }
          }
        }
        &.active {
          .list-content {
            background-color: #409eff;
            border-color: #409eff;
            color: #fff;
            border-radius: 4px;
          }
        }
      }
    }
  }
}
</style>
<style scoped>
ul{list-style: none;}
</style>
